#!/user/bin/env python
# coding:utf-8
"""
Author myYouTh
Date:2020/2/21 002114:15
Desc: 工具类
"""

from collections import Counter
from collections.abc import MutableMapping
import xml.etree.ElementTree as ET
from utils.dataDescriptor import StrDataDescriptor


class ParseXML(MutableMapping):
    """
    封装一个可变字典类，城市的ID作为键，城市名称作为值

    继承抽象基类后必须实现__getitem__(), __iter__(), __len__()、__setitem__()、__delitem__()
    """
    __data = StrDataDescriptor()

    def __init__(self, needparsedata: str):
        """
        初始化
        :param needparsedata: 待解析的xml数据
        """
        super(ParseXML, self).__init__()
        # 字典;缓存数据
        self.__name_to_id = {}
        self.__data = needparsedata

    def __getitem__(self, item):
        print("getitem")
        return self.__name_to_id[item]

    def __setitem__(self, key, value):
        print("setitem")
        self.__name_to_id[key] = value

    def __delitem__(self, key):
        del self.__name_to_id[key]

    def __iter__(self):
        """实例化后的对象是可迭代对象。遍历后得到ID与城市名的元组"""
        if not self.__name_to_id:
            raise NameError("字典数据为空")
        for key, values in self.__name_to_id.items():
            yield key, values

    def __len__(self):
        return len(self.__name_to_id)

    def _parse(self):
        """解析xml格式的文件,得到ID与城市名对应的映射"""
        # 从字符串中读取xml文件，返回一个Element,element对象完成单个节点的处理
        try:
            root = ET.fromstring(self.__data)
            # 遍历单个element节点
            for string in root:
                if ("," in string.text) and (Counter(",")[","] == 1):
                    parse_list = string.text.split(",")
                    self.__name_to_id[parse_list[1]] = parse_list[0]
                else:
                    self.__name_to_id[string.text] = 'null'
        except Exception:
            raise NameError("xml文件可能解析失败")

    def name_id(self):
        if not self.__name_to_id:
            self._parse()
        self.__name_to_id = dict(sorted(self.__name_to_id.items(), key=lambda x: int(x[0])))


